using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace cb0tServer
{
    class Wikipedia
    {
        private Thread thread;
        private bool busy = false;

        private ushort vroom = 0;
        private String query = String.Empty;

        public void Query(ushort vroom, String query)
        {
            if (busy)
            {
                UserPool.Broadcast(vroom, ServerOutboundPackets.AnnoucePacket("wait a few seconds and then try again"));
                return;
            }

            this.vroom = vroom;
            this.query = query;
            this.thread = new Thread(new ThreadStart(this.Work));
            this.thread.Start();
        }

        private void Work()
        {
            this.busy = true;

            StreamReader s;
            HttpWebRequest r;

            try
            {
                r = (HttpWebRequest)WebRequest.Create("http://en.wikipedia.org/wiki/" + Uri.EscapeDataString(query));
                r.UserAgent = "sb0t Chat Server";
                s = new StreamReader(r.GetResponse().GetResponseStream());


                List<String> data = new List<string>();
                String l;
                int c = 0;

                while ((l = s.ReadLine()) != null)
                {
                    if (l.IndexOf("No page with that title exists") > -1 ||
                        l.IndexOf("Wikipedia does not have an article with this exact name") > -1 ||
                        l.IndexOf("Other reasons why this message may be displayed") > -1)
                    {
                        UserPool.Broadcast(this.vroom, ServerOutboundPackets.AnnoucePacket("Unable to find a wiki reference for " + query + "!"));
                        break;
                    }
                    else
                    {
                        if (l.StartsWith("<p>") && l.EndsWith("</p>"))
                        {
                            if (!l.StartsWith("<p><br") && !l.StartsWith("<p><a") && !l.EndsWith(":</p>"))
                            {
                                if (l.IndexOf("may refer to:") == -1)
                                {
                                    switch (c)
                                    {
                                        case 0:
                                            data.Add("10Wikipedia Reference for: 14" + query);
                                            data.Add(" ");
                                            data.Add("06" + RemoveWeirdNumbers(ConvertEntities(RemoveHtmlTags(l))));
                                            break;
                                        case 1:
                                            data.Add(" ");
                                            data.Add("03" + RemoveWeirdNumbers(ConvertEntities(RemoveHtmlTags(l))));
                                            break;
                                        default:
                                            data.Add(" ");
                                            data.Add("06" + RemoveWeirdNumbers(ConvertEntities(RemoveHtmlTags(l))));
                                            break;
                                    }
                                    c++;
                                }
                                if (c > 2) break;
                            }
                        }
                    }
                }
                if (data.Count > 1)
                {
                    foreach (String oline in data.ToArray())
                        UserPool.Broadcast(this.vroom, ServerOutboundPackets.AnnoucePacket(oline));
                }
                else
                {
                    UserPool.Broadcast(this.vroom, ServerOutboundPackets.AnnoucePacket("Unable to find a wiki reference for " + query + "!"));
                }

                s.Close();
            }
            catch { }

            this.busy = false;
        }

        private String RemoveHtmlTags(String unfiltered)
        {
            String result = unfiltered;

            while (((result.IndexOf("<") > -1)
                && (result.IndexOf(">") > -1))
                && (result.IndexOf("<") < result.IndexOf(">")))
            {
                result = result.Substring(0, result.IndexOf("<"))
                    + result.Substring(result.IndexOf(">") + 1);
            }

            return result;
        }

        private String RemoveWeirdNumbers(String unfiltered)
        {
            String result = unfiltered;

            for (int i = 0; i < 50; i++)
            {
                result = result.Replace("[" + i + "]", "");
            }

            return result;
        }

        private String ConvertEntities(String unfiltered)
        {
            String result = unfiltered;

            result = result.Replace("&quot;", "\"");
            result = result.Replace("&amp;", "&");
            result = result.Replace("&#160;", " ");
            result = result.Replace("&lt;", "<");
            result = result.Replace("&gt;", ">");

            return result;
        }
    }
}
